//
//  WLloginController.m
//  WanLian
//
//  Created by muzhuang on 2018/9/11.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLloginController.h"
#import "WLRegisterController.h"
#import "WLRouterBingFlowController.h"
#import "WLWebViewController.h"

@interface WLloginController ()<UITextFieldDelegate>
{
    int resendTime;
    UIButton *btnAgree;
}

@property (nonatomic, strong) UITextField *textPhone;
@property (nonatomic, strong) UITextField *textCode;
@property (nonatomic, strong) UIButton      *btnCode;
@property (nonatomic, strong) UIButton      *btnLogin;
@property (nonatomic, strong) NSTimer       *downTimer;

@end

@implementation WLloginController

- (void)dealloc
{
    [_downTimer invalidate];
    _downTimer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.fd_prefersNavigationBarHidden = YES;
    
    UIButton *registerBtn = [[UIButton alloc] init];//[UIButton buttonWithType:UIButtonTypeCustom];
    registerBtn.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:16];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn setTitleColor:wlBlackColor forState:UIControlStateNormal];
//    registerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [registerBtn addTarget:self action:@selector(goToRegist) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
    WLWkSelf
    [registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view.mas_right).offset(-WLScaleX(10));
        make.top.equalTo(weakSelf.view.mas_top).offset(WL_StatusBarHeight);
        make.size.mas_equalTo(CGSizeMake(80, 44));
    }];
    
    UILabel *labHello = [[UILabel alloc] init];
    labHello.font = [WLCommonTool fontTypePingFangSCMedium:24];
    labHello.textColor = wlBlackColor;
    labHello.text = @"您好！";
    [self.view addSubview:labHello];
    [labHello mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(WLScaleX(82));
        make.left.equalTo(weakSelf.view.mas_left).offset(WLScaleX(32));
    }];
    
    UILabel *labWelcome = [[UILabel alloc] init];
    labWelcome.font = [WLCommonTool fontTypePingFangSCRegular:18];
    labWelcome.textColor = wlDarkGrayColor;
    [self.view addSubview:labWelcome];
    NSMutableAttributedString *strWelcome = [[NSMutableAttributedString alloc] initWithString:@"欢迎使用 天翼链路由器"];
    [strWelcome addAttribute:NSFontAttributeName
                      value:[WLCommonTool fontTypePingFangSCMedium:18]
                      range:NSMakeRange(4, strWelcome.length-4)];
    labWelcome.attributedText = strWelcome;
    [labWelcome mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(WLScaleX(130));
        make.left.equalTo(weakSelf.view.mas_left).offset(WLScaleX(32));
    }];
    
    _textPhone = [[UITextField alloc] init];
    _textPhone.keyboardType = UIKeyboardTypeNumberPad;
    _textPhone.borderStyle = UITextBorderStyleNone;
    _textPhone.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textPhone.delegate = self;
    _textPhone.placeholder = @"请输入您的手机号";
    [self.view addSubview:_textPhone];
    [_textPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(WLScaleX(200));
        make.left.equalTo(weakSelf.view.mas_left).offset(WLScaleX(32));
        make.right.equalTo(weakSelf.view.mas_right).offset(-WLScaleX(32));
        make.height.equalTo(@(WLScaleX(40)));
    }];
    
//    WLUserInfo *user = [[WLUseManager shareUser] getUserInformation];
//    if (user != nil) {
//        _textPhone.text = user.phone;
//    }
    NSString *strPhone = [[NSUserDefaults standardUserDefaults] objectForKey:USER_PHONE];
    _textPhone.text = strPhone;
    
    UIView *phoneLine = [[UIView alloc] init];
    phoneLine.backgroundColor = wlUnderlineColor;
    [self.view addSubview:phoneLine];
    [phoneLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.textPhone);
        make.top.equalTo(weakSelf.textPhone.mas_bottom);
        make.height.equalTo(@(WLScaleX(1)));
    }];
    
    _textCode = [[UITextField alloc] init];
    _textCode.borderStyle = UITextBorderStyleNone;
    _textCode.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textCode.delegate = self;
    _textCode.keyboardType = UIKeyboardTypeNumberPad;
    _textCode.placeholder = @"请输入短信验证码";
    [self.view addSubview:_textCode];
    [_textCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.equalTo(weakSelf.textPhone);
        make.top.equalTo(weakSelf.textPhone.mas_bottom).offset(WLScaleX(10));
//        make.left.equalTo(weakSelf.view.mas_left).offset(WLScaleX(32));
//        make.right.equalTo(weakSelf.view.mas_right).offset(-WLScaleX(32));
        make.width.equalTo(@(WLScaleX(206)));
    }];
    
    UIView *verticalLine = [[UIView alloc] init];
    verticalLine.backgroundColor = wlUnderlineColor;
    [self.view addSubview:verticalLine];
    [verticalLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.textCode.mas_top).offset(WLScaleX(10));
        make.left.equalTo(weakSelf.view.mas_left).offset(WLScaleX(240));
        make.size.mas_equalTo(CGSizeMake(WLScaleX(1), WLScaleX(20)));
    }];
    
    _btnCode = [[UIButton alloc] init];
    _btnCode.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:16];
    [_btnCode setTitleColor:wlUIColorRGB(0x1A59E2) forState:UIControlStateNormal];
    _btnCode.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_btnCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_btnCode addTarget:self action:@selector(getCodeAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnCode];
    [_btnCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(verticalLine.mas_right).offset(WLScaleX(2));
        make.top.equalTo(weakSelf.textCode.mas_top);
        make.bottom.equalTo(weakSelf.textCode.mas_bottom);
        make.right.equalTo(weakSelf.textPhone.mas_right);
    }];
    
    
    UIView *textLine = [[UIView alloc] init];
    textLine.backgroundColor = wlUnderlineColor;
    [self.view addSubview:textLine];
    [textLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.textPhone);
        make.top.equalTo(weakSelf.textCode.mas_bottom);
        make.height.equalTo(@(WLScaleX(1)));
    }];
    
    _btnLogin = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL-WLScaleX(62), WLScaleX(47))];
    CAGradientLayer *gradientBtn = [CAGradientLayer layer];
    gradientBtn.frame = _btnLogin.bounds;  // 设置显示的frame
    gradientBtn.colors = @[(__bridge id)wlUIColorRGB(0x1A59E2).CGColor,(__bridge id)wlUIColorRGB(0x2292F5).CGColor]; // 设置渐变颜色
    gradientBtn.startPoint = CGPointMake(0, 0);
    gradientBtn.endPoint = CGPointMake(1, 0);
    [_btnLogin.layer insertSublayer:gradientBtn atIndex:0];
    
    _btnLogin.layer.cornerRadius = 5;//WLScaleX(5);
    _btnLogin.layer.masksToBounds = YES;
//    [_btnLogin setBackgroundColor:wlUnderlineColor];
    _btnLogin.titleLabel.font = [WLCommonTool fontTypePingFangSCMedium:16];
    [_btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnLogin setTitle:@"登录" forState:UIControlStateNormal];
    [_btnLogin addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnLogin];
    [_btnLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.textCode.mas_bottom).offset(WLScaleX(40));
        make.left.right.equalTo(weakSelf.textPhone);
        make.height.equalTo(@(WLScaleX(47)));
    }];
//    _btnLogin.enabled = NO;
    
    CGFloat left = (WIDTH_SCREEN_WL-175-30)/2.0;//labwidth大约是175
    btnAgree = [[UIButton alloc] init];
    [btnAgree setImage:[UIImage imageNamed:@"disagree_btn"] forState:UIControlStateNormal];
    [btnAgree setImage:[UIImage imageNamed:@"agree_btn"] forState:UIControlStateSelected];
    [btnAgree addTarget:self action:@selector(agreeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAgree];
    btnAgree.selected = YES;
    [btnAgree mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.btnLogin.mas_bottom).offset(WLScaleX(10));
//        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.left.equalTo(weakSelf.view.mas_left).offset(left);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    UIButton *btnAgreement = [[UIButton alloc] init];
    btnAgreement.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:12];
    [btnAgreement setTitleColor:wlLightTextColor forState:UIControlStateNormal];
    [btnAgreement setTitle:@"已阅读并同意《用户服务协议》" forState:UIControlStateNormal];
    [btnAgreement addTarget:self action:@selector(agreementAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAgreement];
    [btnAgreement mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.btnLogin.mas_bottom).offset(WLScaleX(15));
//        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.left.equalTo(weakSelf.view.mas_left).offset(left+30);
        make.height.equalTo(@(20));
    }];
    
    /*
    UIButton *btnWXLogin = [[UIButton alloc] init];
    [btnWXLogin setBackgroundImage:[UIImage imageNamed:@"login_wechat"] forState:UIControlStateNormal];
    [btnWXLogin addTarget:self action:@selector(weixinLoginAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnWXLogin];
    [btnWXLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(-WLScaleX(40));
        make.size.mas_equalTo(CGSizeMake(44, 44));
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    UIView *leftLine = [[UIView alloc] init];
    leftLine.backgroundColor = wlUIColorRGB(0xF2F2F2);
    [self.view addSubview:leftLine];
    [leftLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(WLScaleX(100), WLScaleX(1)));
        make.right.equalTo(btnWXLogin.mas_left).offset(-WLScaleX(12));
        make.centerY.equalTo(btnWXLogin.mas_centerY);
    }];
    
    UIView *rigthLine = [[UIView alloc] init];
    rigthLine.backgroundColor = wlUIColorRGB(0xF2F2F2);
    [self.view addSubview:rigthLine];
    [rigthLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(WLScaleX(100), WLScaleX(1)));
        make.left.equalTo(btnWXLogin.mas_right).offset(WLScaleX(12));
        make.centerY.equalTo(btnWXLogin.mas_centerY);
    }];
    
    UILabel *labWechatLogin = [[UILabel alloc] init];
    labWechatLogin.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labWechatLogin.textColor = wlDarkGrayColor;
    labWechatLogin.text = @"其他方式登录";
    [self.view addSubview:labWechatLogin];
    [labWechatLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(btnWXLogin.mas_top).offset(-WLScaleX(20));
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    */
}

-(void)agreementAction
{
    WLWebViewController *webView = [[WLWebViewController alloc] init];
    webView.urlStr = [NSString stringWithFormat:@"%@/help/agreement.html",[WLCommonTool getWebHost]];
    webView.titleStr = @"用户服务协议";
    [self.navigationController pushViewController:webView animated:YES];
}

- (void)goToRegist
{
    WLRegisterController *registerController = [[WLRegisterController alloc] init];
    [self.navigationController pushViewController:registerController animated:YES];
//    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)getCodeAction
{
    if ([WLCommonTool isMobileNumber:_textPhone.text]==NO) {
        [self showHUDMessage:@"请输入正确的手机号"];
        return;
    }
    resendTime = 60;
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"valitation/msg/code" withParamsDic:@{@"mobile":_textPhone.text} success:^(NSDictionary *successDict) {
        if (weakSelf.downTimer == nil)
        {
            weakSelf.downTimer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timingAction) userInfo:nil repeats:YES];
            [weakSelf.btnCode setTitleColor:wlLightTextColor forState:UIControlStateNormal];
            weakSelf.btnCode.userInteractionEnabled = NO;
        }
        NSString *strMsg = successDict[@"message"];
        if (strMsg != nil&&[strMsg isKindOfClass:[NSNull class]]==NO)
        {
            [weakSelf showHUDMessage:strMsg];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)timingAction
{
    resendTime -= 1;
    NSString *string = [NSString stringWithFormat:@"%ds",resendTime];
    [self.btnCode setTitle:string forState:UIControlStateNormal];
    if (resendTime < 1) {
        [self.btnCode setTitle:@"重新发送" forState:UIControlStateNormal];
        self.btnCode.userInteractionEnabled = YES;
        [self.btnCode setTitleColor:wlUIColorRGB(0x1A59E2) forState:UIControlStateNormal];
        resendTime = 60;
        [_downTimer invalidate];
        _downTimer = nil;
    }
}

- (void)loginAction
{
    [[WLSocketManager sharedSocketManager] userManualdisconnect];
    if ([WLCommonTool isMobileNumber:_textPhone.text]==NO) {
        [self showHUDMessage:@"请输入正确的手机号"];
        return;
    }
    if (_textCode.text.length<6) {
        [self showHUDMessage:@"请输入正确的验证码"];
        return;
    }
    if (btnAgree.selected==NO) {
        [self showHUDMessage:@"请阅读并同意用户服务协议"];
        return;
    }
    [self.view endEditing:YES];
    NSDictionary *params = @{@"mobile":_textPhone.text,@"code":_textCode.text};
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/login/mobile" withParamsDic:params success:^(NSDictionary *successDict) {
        WLUserInfo *user = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:user];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        if (user.sessionId !=nil)
        {
            [userDefaults setObject:user.sessionId forKey:USER_SESSION];
        }
        if (user.phone !=nil) {
            [userDefaults setObject:user.phone forKey:USER_PHONE];
        }
        [userDefaults synchronize];
//        NSDictionary *dicto = successDict[@"object"];
//        NSArray *arrKey = dicto.allKeys;
//        for (int i=0; i<arrKey.count; i++) {
//            NSString *key = arrKey[i];
//            WLLog(@"key:%@,value:%@,class:%@",key,dicto[key],[dicto[key] class]);
//        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kNOTIFICATION_LOGINED object:nil];
        if (user.devCount>0)
        {
            [[WLUseManager shareUser] requestRouterInfo];
            [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
//            if (user.sord==nil) {
//                [weakSelf.navigationController dismissViewControllerAnimated:NO completion:^{
//                    [WLCommonTool pushToBingFlowController];
//                }];
//            }
//            else
//            {
//                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
//            }
        }
        else
        {
            [weakSelf goToDeviceBingding];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        NSLog(@"%@", error);
    } inView:self.view];
}

- (void)agreeAction:(UIButton *)btnA
{
    btnAgree.selected = !btnAgree.selected;
}

- (void)weixinLoginAction
{
    
}

- (void)goToDeviceBingding
{
    WLRouterBingFlowController *flowController = [[WLRouterBingFlowController alloc] init];
    flowController.isPresented = YES;
    flowController.isPopDisabled = YES;
    [self.navigationController pushViewController:flowController animated:YES];
}

#pragma mark - UITextDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([textField isEqual:_textCode]) {
        if (textField.text.length >= 6 && string.length != 0) {
            return NO;
        }
    }
    if ([textField isEqual:_textPhone]) {
        if (textField.text.length >= 11 && string.length != 0) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
